<template>
	<view class="page-wrapper">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="nav-left" @click="goBack">
				<u-icon name="arrow-left" size="27" color="#fff"></u-icon>
			</view>
			<view class="nav-title">忘记密码</view>
			<view class="nav-right"></view>
		</view>

		<view class="forget-container">
			<u-form ref="form" :model="formData" :rules="rules">
				<view class="form">
					<u-form-item prop="phone">
						<u-input v-model="formData.phone" type="number" placeholder="请输入手机号" class="input"
							border="bottom" style="height: 88rpx;">
							<template #prefix>
								<image src="@/static/img/login/icon-iphone@2x.png" mode="aspectFit"
									style="height: 39rpx;width: 27rpx; margin-right: 15rpx;margin-left: 11rpx;"></image>
							</template>
							<template #suffix>
								<u-text :text="countdown > 0 ? `${countdown}s后重新发送` : '发送验证码'" color="#ff5033"
									@click="sendCode" :disabled="countdown > 0"
									:customStyle="{ fontSize: '28rpx' }"></u-text>
							</template>
						</u-input>
					</u-form-item>

					<u-form-item prop="code">
						<u-input v-model="formData.code" type="number" placeholder="请输入手机验证码" class="input"
							border="bottom" style="height: 88rpx;">
							<template #prefix>
								<u-icon name="email" size="27" color="#909399"></u-icon>
							</template>
						</u-input>
					</u-form-item>

					<u-form-item prop="password">
						<u-input v-model="formData.password" :type="showPassword ? 'text' : 'password'"
							placeholder="请输入新密码" class="input" border="bottom" style="height: 88rpx;">
							<template #prefix>
								<u-icon name="lock" size="27" color="#909399"></u-icon>
							</template>
							<template #suffix>
								<u-icon :name="showPassword ? 'eye' : 'eye-off'" size="28" color="#909399"
									@click="togglePassword"></u-icon>
							</template>
						</u-input>
					</u-form-item>

					<u-form-item prop="confirmPassword">
						<u-input v-model="formData.confirmPassword" :type="showConfirmPassword ? 'text' : 'password'"
							placeholder="请确认新密码" class="input" border="bottom" style="height: 88rpx;">
							<template #prefix>
								<u-icon name="lock" size="27" color="#909399"></u-icon>
							</template>
							<template #suffix>
								<u-icon :name="showConfirmPassword ? 'eye' : 'eye-off'" size="28" color="#909399"
									@click="toggleConfirmPassword"></u-icon>
							</template>
						</u-input>
					</u-form-item>
					<u-text text="密码必须为6-20数字和字母组合！" color="#999" size="12" style="margin-left: 10rpx;"></u-text>

					<u-button type="primary" @click="resetPassword" color="#ff5033" text="完成"
						:customStyle="{ borderRadius: '10rpx', height: '88rpx', fontSize: '32rpx', marginTop: '40rpx' }">
					</u-button>
					<view class="login-options">
						<view class="login-options-item" @click="goToLogin">
							<u-text text="记起密码？去登录" color="#ff5033" size="16"></u-text>
						</view>
					</view>
				</view>
			</u-form>
		</view>
	</view>
</template>

<script>
import api from '@/api/index.js'
import md5 from '@/utils/md5.js'
export default {
	data() {
		return {
			formData: {
				phone: '',
				code: '',
				password: '',
				confirmPassword: ''
			},
			countdown: 0,
			timer: null,
			showPassword: false,
			showConfirmPassword: false,
			rules: {
				phone: [
					{
						type: 'string',
						required: true,
						message: '请输入手机号',
						trigger: ['blur', 'change']
					},
					{
						validator: (rule, value, callback) => {
							if (!/^1[3-9]\d{9}$/.test(value)) {
								return callback(new Error('手机号格式不正确'))
							}
							return callback()
						},
						trigger: ['blur', 'change']
					}
				],
				code: [
					{
						type: 'string',
						required: true,
						message: '请输入手机验证码',
						trigger: ['blur', 'change']
					},
				],
				password: [
					{
						type: 'string',
						required: true,
						message: '请输入新密码',
						trigger: ['blur', 'change']
					},
					{
						validator: (rule, value, callback) => {
							const passwordReg = /^(?=.*[0-9])(?=.*[a-zA-Z])[0-9a-zA-Z]{6,20}$/
							if (!passwordReg.test(value)) {
								return callback(new Error('密码必须为6-20位数字字母组合'))
							}
							return callback()
						},
						trigger: ['blur', 'change']
					}
				],
				confirmPassword: [
					{
						type: 'string',
						required: true,
						message: '请确认新密码',
						trigger: ['blur', 'change']
					},
					{
						validator: (rule, value, callback) => {
							if (value !== this.formData.password) {
								return callback(new Error('两次密码输入不一致'))
							}
							return callback()
						},
						trigger: ['blur', 'change']
					}
				]
			}
		}
	},
	computed: {
		statusBarHeight() {
			return uni.getSystemInfoSync().statusBarHeight || 0
		}
	},
	methods: {
		goToLogin() {
			uni.navigateTo({
				url: '/pages/login/login_qt'
			})
		},
		togglePassword() {
			this.showPassword = !this.showPassword
		},
		toggleConfirmPassword() {
			this.showConfirmPassword = !this.showConfirmPassword
		},
		goBack() {
			console.log('goBack方法被调用')
			// 获取当前页面栈
			const pages = getCurrentPages()
			console.log('当前页面栈长度:', pages.length)

			if (pages.length > 1) {
				// 有上一页，可以返回
				uni.navigateBack()
			} else {
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/login/login_qt'
					})
				}, 1500)
			}
		},
		async sendCode() {
			if (this.countdown > 0) return

			// 验证手机号字段
			try {
				await this.$refs.form.validateField('phone')
			} catch (error) {
				return
			}

			try {
				uni.showLoading({ title: '发送中...' })
				const result = await api.userApi.sendCode({ mobile: this.formData.phone, salt: '1234' })
				uni.hideLoading()
				if (result.r === 0) {
					uni.showToast({ title: result.msg || '验证码已发送', icon: 'success' })
					this.startCountdown()
				} else {
					uni.showToast({ title: result.msg || '发送失败', icon: 'none' })
				}
			} catch (error) {
				uni.hideLoading()
				uni.showToast({ title: '网络异常，请重试', icon: 'none' })
			}
		},
		startCountdown() {
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
			this.countdown = 60
			this.timer = setInterval(() => {
				this.countdown--
				if (this.countdown <= 0) {
					clearInterval(this.timer)
					this.timer = null
				}
			}, 1000)
		},
		// 获取用户IP地址
		async getUserIp() {
			try {
				const result = await api.userApi.getIp()
				console.log('获取IP结果:', result)
				if (result.r === 0) {
					this.userIp = result.data
					console.log('用户IP地址:', this.userIp)
				} else {
					console.error('获取IP失败:', result.msg)
					// 如果获取IP失败，使用默认值
					this.userIp = '0.0.0.0'
				}
			} catch (error) {
				console.error('获取IP异常:', error)
				this.userIp = '0.0.0.0'
			}
		},
		async resetPassword() {
			// 验证整个表单
			try {
				await this.$refs.form.validate()
			} catch (error) {
				console.log('表单验证失败:', error)
				return
			}

			try {
				uni.showLoading({ title: '重置中...' })

				await this.getUserIp()

				// 调用重置密码API
				const params = {
					mobile: this.formData.phone,
					pwd: md5(this.formData.password), // 需要MD5加密
					code: this.formData.code,
					last_login_ip: this.userIp,
					salt: '1234'
				}
				const result = await api.userApi.resetAccountPassword(params)

				uni.hideLoading()

				if (result.r === 0) {
					uni.showToast({
						title: '密码重置成功',
						icon: 'success'
					})

					// 设置重置成功标记
					uni.setStorageSync('is_forget', true)

					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login_qt'
						})
					}, 1500)
				} else {
					uni.showToast({
						title: result.msg || '重置失败',
						icon: 'none'
					})
				}
			} catch (error) {
				uni.hideLoading()
				uni.showToast({
					title: '重置失败，请重试',
					icon: 'none'
				})
				console.error('重置密码失败:', error)
			}
		}
	},

	onUnload() {
		if (this.timer) {
			clearInterval(this.timer)
		}
	}
}
</script>

<style scoped>
.page-wrapper {
	background-color: #f8f8f8;
	min-height: 100vh;
}

.status-bar {
	background-color: #ff5033;
}

.navbar {
	display: flex;
	align-items: center;
	height: 88rpx;
	background-color: #ff5033;
	padding: 0 30rpx;
	position: relative;
}

.nav-left {
	width: 80rpx;
	height: 88rpx;
	display: flex;
	align-items: center;
	justify-content: flex-start;
	cursor: pointer;
	z-index: 10;
}

.back-icon {
	width: 44rpx;
	height: 44rpx;
}

.nav-title {
	flex: 1;
	text-align: center;
	font-size: 36rpx;
	color: #fff;
	font-weight: 500;
}

.nav-right {
	width: 80rpx;
	height: 88rpx;
}

.forget-container {
	padding: 40rpx;
	background-color: #f8f8f8;
	min-height: calc(100vh - 88rpx);
}

.form {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 100rpx 50rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.input-group {
	margin-bottom: 40rpx;
}

.code-group {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.input {
	width: 100%;
	height: 88rpx;
	border-radius: 10rpx;
	padding: 0 20rpx;
	font-size: 32rpx;
	box-sizing: border-box;
}

.code-input {
	flex: 1;
}

.code-btn {
	width: 200rpx;
	height: 88rpx;
	background-color: #ff5033;
	color: #fff;
	border: none;
	border-radius: 10rpx;
	font-size: 28rpx;
	line-height: 88rpx;
}

.code-btn:disabled {
	background-color: #ccc;
}

.submit-btn {
	width: 100%;
	height: 88rpx;
	background-color: #ff5033;
	color: #fff;
	border: none;
	border-radius: 10rpx;
	font-size: 32rpx;
	margin-top: 40rpx;
}

.login-options {
	display: flex;
	justify-content: center;
	margin-top: 40rpx;
}
</style>